package io.github.wslxm.springbootplus2.starter.redis.config.resolver;

import io.github.wslxm.springbootplus2.starter.redis.config.next.CacheThreadLocal;
import io.github.wslxm.springbootplus2.starter.redis.constant.CacheSeparateConst;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.CacheResolver;

import java.util.Collection;
import java.util.Collections;


/**
 * redis 动态前缀处理对象
 * <P>
 *    通过 TenantLocal 传递动态前缀, 建议使用过滤器统一设置
 * </P>
 * @author 王松
 * @mail 1720696548@qq.com
 * @date 2024/9/29 17:36 
 */
public class CachePrefixResolver implements CacheResolver {

    private final CacheManager cacheManager;

    public CachePrefixResolver(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }


    @Override
    public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
        String cacheName = context.getOperation().getCacheNames().iterator().next();
        String tenantId = CacheThreadLocal.getPrefix();
        if (tenantId != null) {
            cacheName = tenantId + CacheSeparateConst.SEPARATE + cacheName;
        }
        return Collections.singletonList(cacheManager.getCache(cacheName));
    }
}